package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils2 {
    public static WebDriver driver;
    public static WebDriver createDriver(){
        if(driver == null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");//    --remote-allow-origins=*
            driver= new ChromeDriver(options);
            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    public void ScreenShot(String str) throws IOException {
        //  ./src/test/java/image
        //                       /2025-05-18
        //                                  /test01_023523.png

        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());
        //./src/test/java/images/2025-03-02/test01_13972011.png
        String filename = "./src/test/java/images/"+dirTime+"/"+str + "_"+fileTime+".png";

        //截图这个动作
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        //放入文件夹
        FileUtils.copyFile(srcFile, new File(filename));
    }

}
